#pragma once
#include "ApplicationBase.hpp"
#include <entt/entt.hpp>
#include <SDL.h>
#include "imgui.h"
#include <map>
#include <functional>
#include "ScriptComponent.hpp"

class Engine;

class Editor : public ApplicationBase {
public:
    Editor(Engine* engine);
    ~Editor();
    bool initialize() override;
    void processInput() override;
    void update(float deltaTime) override;
    void render() override;
    void shutdown() override;
    std::string getName() const override { return "EditorApplication"; }
private:
    // 渲染编辑器UI
    void renderMainMenu();
    void renderEntityList();
    void renderComponentEditor(entt::entity entity);
    void renderSceneView();
    void renderInspector();
    void renderResourceView();
    void renderStats();
    void renderCreateEntityPopup();
    void renderAddComponentPopup();
    // 脚本相关
    void renderPropertyEditor(const std::string& scriptName, ScriptComponent& scriptComp);
    void renderPropertyField(const PropertyDescriptor& prop, PropertyValue& value);
private:
    void createEmptyScene();
    void createEntity();
    void addComponentToEntity(entt::entity entity, const std::string& componentType);
    void handleEntityDeletion(entt::entity entity);
    // 场景视图相关
    entt::entity findEntityAtPosition(float x, float y);
    void handleSceneViewInput();
    void drawGrid(ImDrawList* drawList, ImVec2 windowPos, ImVec2 windowSize, float zoom, ImVec2 pan);
    ImVec2 screenToWorld(float screenX, float screenY);
    ImVec2 worldToScreen(float worldX, float worldY);
    // 从engine获取registry
    entt::registry& getRegistry();
private:
    Engine* engine;
    SDL_Renderer* renderer;
private:
    bool editorMode = true;
    bool showDemoWindow = false;
    bool showEntityList = true;
    bool showInspector = true;
    bool showSceneView = true;
    bool showResourceView = false;
    bool showStats = true;
    bool showCreateEntityPopup = false;
    bool showAddComponentPopup = false;

    entt::entity selectedEntity = entt::null;

    // 场景视图相关
    ImVec2 sceneViewSize = ImVec2(800, 600);
    ImVec2 sceneViewPos = ImVec2(0, 0);
    float sceneZoom = 1.0f;
    ImVec2 scenePan = ImVec2(0, 0);
    bool isSceneViewHovered = false;

    // 资源浏览器相关
    char assetPathBuffer[256] = "assets/";
    
    // 组件类型映射
    std::map<std::string, std::function<void(entt::entity)>> componentCreators;    
};